package com.wnxy.sddfp.bank.mq;

import com.wnxy.sddfp.common.constant.MQConstant;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

//@Configuration
public class RabbitConfig {

    /**
     * 消息的转换器，发送对象消息需要配置转换器：把对象转换为json
     * @return
     */
    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 交换机：sddf-exchange-account
     * 队列：sddf-queue-account
     * 路由：account.#
     */
    @Bean("exchangeAccount")
    public Exchange orderExchange() {
        return new TopicExchange(MQConstant.SDDF_EXCHANGE_ACCOUNT, true, false);
    }
    // 队列
    @Bean("queueAccount")
    public Queue ttlOrderQueue() {
        Map params = new HashMap();
        return new Queue(MQConstant.SDDF_QUEUE_ACCOUNT, true, false, false, params);
    }
    // 绑定
    @Bean
    public Binding bindTTLOrderQueue(
            @Qualifier("queueAccount") Queue queue,
            @Qualifier("exchangeAccount") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange)
                .with(MQConstant.SDDF_ACCOUNT_ROUTING).noargs();
    }

    @Bean
    public RabbitAdmin rabbitAdmin(
            ConnectionFactory factory,
            Exchange exchangeAccount,
            Queue queueAccount) {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(factory);
        rabbitAdmin.setAutoStartup(true);
        rabbitAdmin.declareExchange(exchangeAccount);
        rabbitAdmin.declareQueue(queueAccount);
        return rabbitAdmin;
    }
}